package role_v1

import (
	"context"
	"errors"
	"gf-xb-api/internal/dao"
	"gf-xb-api/internal/model/dto"
	"gf-xb-api/utility/xpermission"
	"gf-xb-api/utility/xstr"

	"github.com/gogf/gf/v2/frame/g"
)

func (s *sRole) Update(ctx context.Context, in *dto.UpdateRoleInput) (err error) {

	// 参数检查
	if in == nil {
		return errors.New("参数信息为空")
	}

	if in.Id == nil || in.Name == nil || xstr.IsBlank(*in.Name) {
		return errors.New("参数不正确")
	}

	c, err := dao.SysRole.Ctx(ctx).WherePri(in.Id).Count()
	if err != nil {
		return err
	}

	if c == 0 {
		return errors.New("角色不存在或已被删除")
	}

	remark := in.Remark
	if in.Remark != nil && xstr.IsBlank(*in.Remark) {
		remark = nil
	}

	userUUID := xpermission.GetLoginUserUUID(ctx)
	cols := dao.SysRole.Columns()
	_, err = dao.SysRole.Ctx(ctx).Data(g.Map{
		cols.Name:      *in.Name,
		cols.Remark:    remark,
		cols.UpdatedBy: userUUID,
	}).WherePri(in.Id).Update()
	if err != nil {
		return err
	}

	return nil
}
